<?php

namespace backend\controllers;

use Yii;
use common\models\TryRec;
use backend\models\TryRecSearch;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use services\models\Product;

/**
 * TryRecController implements the CRUD actions for TryRec model.
 */
class TryRecController extends MyController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all TryRec models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new TryRecSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        $product_info = Product::getGoodsInfo();
        $dataArray = [];
        if(!empty($product_info))
        {
            foreach($product_info as $v)
            {
                $dataArray[$v['product_id']] = ['goods_id'=>$v['goods_id'], 'goods_name'=>$v['goods_name']] ;
            }
        }
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'dataArray'=>$dataArray
        ]);
    }

    /**
     * Displays a single TryRec model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new TryRec model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new TryRec();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index', 'id' => $model->try_recommend_id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing TryRec model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index', 'id' => $model->try_recommend_id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing TryRec model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the TryRec model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return TryRec the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = TryRec::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    public function actionRefreshCache()
    {
        $datetime = date('Y-m-d 00:00:00');
        $connection = Yii::$app->db;
        
        $sql = "SELECT * FROM d_try.`try_rec` where `status`=1 ORDER BY display_position,recommend_time desc;";     
        $result = $connection->createCommand($sql)->queryAll();
        if(!empty($result))
        {
            $flag1 = $flag2 = $flag3 = $flag4 = 0;
            $index_manage = array();
            foreach($result as $k=>$v)
            {
                $product_info1 = Product::findOne(['product_id'=>$v['product1']]);
                $product_info2 = Product::findOne(['product_id'=>$v['product2']]);
                $product_info3 = Product::findOne(['product_id'=>$v['product3']]);
                if($v['recommend_time'] >= $datetime)
                {
                    $index_manage[$v['display_position']][$k]['product_id1'] = $v['product1'];
                    $index_manage[$v['display_position']][$k]['product_id2'] = $v['product2'];
                    $index_manage[$v['display_position']][$k]['product_id3'] = $v['product3'];
                    $index_manage[$v['display_position']][$k]['goods_id1'] = $product_info1->goods_id;
                    $index_manage[$v['display_position']][$k]['goods_id2'] = $product_info2->goods_id;
                    $index_manage[$v['display_position']][$k]['goods_id3'] = $product_info3->goods_id;
                    $index_manage[$v['display_position']][$k]['pic'] = $v['pic1'];
                    $index_manage[$v['display_position']][$k]['recommend_time'] = $v['recommend_time'];
                }elseif(($v['display_position'] == 1 && $flag1 != 1) || ($v['display_position'] == 2 && $flag2 != 1) || ($v['display_position'] == 3 && $flag3 != 1) || ($v['display_position'] == 4 && $flag4 != 1))
                {
                    $index_manage[$v['display_position']][$k]['product_id1'] = $v['product1'];
                    $index_manage[$v['display_position']][$k]['product_id2'] = $v['product2'];
                    $index_manage[$v['display_position']][$k]['product_id3'] = $v['product3'];
                    $index_manage[$v['display_position']][$k]['goods_id1'] = $product_info1->goods_id;
                    $index_manage[$v['display_position']][$k]['goods_id2'] = $product_info2->goods_id;
                    $index_manage[$v['display_position']][$k]['goods_id3'] = $product_info3->goods_id;
                    $index_manage[$v['display_position']][$k]['pic'] = $v['pic1'];
                    $index_manage[$v['display_position']][$k]['recommend_time'] = $v['recommend_time'];
                    $flag1 = $v['display_position'] == 1 ? 1 : 0;
                    $flag2 = $v['display_position'] == 2 ? 1 : 0;
                    $flag3 = $v['display_position'] == 3 ? 1 : 0;
                    $flag4 = $v['display_position'] == 4 ? 1 : 0;
                }
            }
            \Yii::$app->redis_index->set('try_rec',  serialize($index_manage));
        }else
        {
            \Yii::$app->redis_index->set('try_rec', '');
        }
        $json_array = ['flag' => 1];
        return json_encode($json_array);
    }
    
}
